﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;

public partial class Default3 : System.Web.UI.Page
{
    string strCon = System.Configuration.ConfigurationManager.ConnectionStrings["xxnewsConnectionString"].ConnectionString;
    SqlConnection sqlcon;
    SqlCommand sqlcom;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["pn"] == "" || Session["pn"] == null)
        {
            Response.Redirect("default.aspx?lb=审批");
        }
        if (Session["pngeren"] == "" || Session["pngeren"] == null)
        {
            Response.Redirect("default.aspx?lb=审批");
        }
        if (Session["pn"].ToString().Contains("材料科") == false)
        {
            Response.Redirect("default.aspx?lb=审批");
        }
        Label1.Text = Session["pn"].ToString();
        Label2.Text = Session["pngeren"].ToString();
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        for (int i = 0; i < GridView1.Rows.Count; i++)
        {

            string txt1 = ((TextBox)GridView1.Rows[i].Cells[14].FindControl("TextBox3")).Text;
            string txt2 = ((TextBox)GridView1.Rows[i].Cells[15].FindControl("TextBox4")).Text;
            string card = ((DropDownList)GridView1.Rows[i].Cells[16].FindControl("ddlCardNum")).SelectedValue.Trim();
            if (txt1.Length == 0)
            {
                string jinggao1 = "<SCRIPT language=javascript>alert('";
                jinggao1 += "请输入序号为 " + (GridView1.PageSize * GridView1.PageIndex + i + 1).ToString() + " 的领取人！";
                jinggao1 += "');</SCRIPT>";
                ClientScript.RegisterStartupScript(this.GetType(), "aa3", jinggao1);

                //ScriptManager.RegisterStartupScript(UpdatePanel1, this.GetType(), "", jinggao1, true);
                return;
            }
            if (txt2.Length == 0)
            {
                string jinggao1 = "<SCRIPT language=javascript>alert('";
                jinggao1 += "请选择序号为 " + (GridView1.PageSize * GridView1.PageIndex + i + 1).ToString() + " 的领取时间！";
                jinggao1 += "');</SCRIPT>";
                ClientScript.RegisterStartupScript(this.GetType(), "aa3", jinggao1);

                //ScriptManager.RegisterStartupScript(UpdatePanel1, this.GetType(), "", jinggao1, true);
                return;
            }
            if (string.IsNullOrEmpty(card))
            {
                string jinggao1 = "<SCRIPT language=javascript>alert('";
                jinggao1 += "请输入序号为 " + (GridView1.PageSize * GridView1.PageIndex + i + 1).ToString() + " 的分拨油卡卡号！";
                jinggao1 += "');</SCRIPT>";
                ClientScript.RegisterStartupScript(this.GetType(), "aa3", jinggao1);

                //ScriptManager.RegisterStartupScript(UpdatePanel1, this.GetType(), "", jinggao1, true);
                return;
            }

        }

        //检查是否已受理过
        using (sqlcon = new SqlConnection(strCon))
        {
            sqlcon.Open();
            try
            {
                string sqlstr0 = "select zt from ranyouxiaohao where id=" + Convert.ToInt32(Request.QueryString["id"]);
                sqlcom = new SqlCommand(sqlstr0, sqlcon);
                sqlcom.Connection = sqlcon;
                if (sqlcom.ExecuteScalar().ToString() != "4")
                {
                    throw new Exception("该记录不存在或者已被受理过！请勿通过后退功能重复操作！");
                }
            }
            catch (Exception ex)
            {
                string jinggao1 = "<SCRIPT language=javascript>alert('";
                jinggao1 += ex.Message;
                jinggao1 += "');document.location.href='clk_shoulilist.aspx';</SCRIPT>";
                ClientScript.RegisterStartupScript(this.GetType(), "aa3", jinggao1);
                return;
            }
            finally { sqlcon.Close(); }
        }

        bool issuccess = true;
        try
        {
            //更新明细表
            using (sqlcon = new SqlConnection(strCon))
            {
                sqlcon.Open();
                SqlTransaction transaction;
                transaction = sqlcon.BeginTransaction("ranyoushouliTransaction");
                try
                {
                    //其实只有一条数据。。。。。。。
                    for (int i = 0; i < GridView1.Rows.Count; i++)
                    {
                        int id = Convert.ToInt32(Request.QueryString["id"]);
                        string lingquren = ((TextBox)GridView1.Rows[i].Cells[14].FindControl("TextBox3")).Text;
                        string lingqutime = ((TextBox)GridView1.Rows[i].Cells[15].FindControl("TextBox4")).Text;
                        lingqutime = DateTime.Parse(lingqutime).ToString("yyyy-MM-dd");
                        string card = ((DropDownList)GridView1.Rows[i].Cells[15].FindControl("ddlCardNum")).SelectedValue;
                        decimal jine = (decimal)this.GridView1.DataKeys[i]["jine"];
                        //更新燃油计划表。
                        string sqlstr = "update ranyouxiaohao set lingquren='" + lingquren + "',lingqutime='" + lingqutime + "' where id=" + id;
                        sqlcom = new SqlCommand(sqlstr, sqlcon);
                        sqlcom.Connection = sqlcon;
                        sqlcom.Transaction = transaction;
                        sqlcom.ExecuteNonQuery();
                        //更新油卡主卡明细表
                        ////    先删除原表中计划ID相同的数据，防止重复
                        //sqlstr = "delete youkaguanli_maincard_detail where planid=" + id ;
                        //sqlcom = new SqlCommand(sqlstr, sqlcon);
                        //sqlcom.Connection = sqlcon;
                        //sqlcom.Transaction = transaction;
                        //sqlcom.ExecuteNonQuery();
                        //sqlstr = "delete youkaguanli_card_detail where planid=" + id;
                        //sqlcom = new SqlCommand(sqlstr, sqlcon);
                        //sqlcom.Connection = sqlcon;
                        //sqlcom.Transaction = transaction;
                        //sqlcom.ExecuteNonQuery();
                        //    新增一条记录
                        sqlstr = @"
insert into youkaguanli_maincard_detail (changetime,amount,balance,addname,addip,planid)
select top(1) cast('{0}'as smalldatetime) ,{1},balance+({1}),'{2}','{3}',{4}
from youkaguanli_maincard_detail
where changetime<=cast('{0}'as smalldatetime) or id=1
order by changetime desc,addtime desc,id desc";
                        //时间为领取时间，操作人为当前用户。分卡的分拨操作人为领取人。
                        sqlcom = new SqlCommand(string.Format(sqlstr, lingqutime, jine * -1/*从主卡中扣除*/, Label2.Text, Page.Request.UserHostAddress.ToString().Trim(), id), sqlcon);
                        sqlcom.Connection = sqlcon;
                        sqlcom.Transaction = transaction;
                        sqlcom.ExecuteNonQuery();
                        //    更新之后的记录，更新主卡余额,因为刚添加的一定是changetime所在天的最后一条，因此只需更新日期之后的
                        sqlstr = @"UPDATE t SET balance = balance +({1})
FROM (select ROW_NUMBER() over (order by changetime desc,addtime desc,id desc) as i,zhuka.*
from youkaguanli_maincard_detail as zhuka) t
where changetime>cast('{0}'as smalldatetime)";
                        sqlcom = new SqlCommand(string.Format(sqlstr, lingqutime, jine * -1/*从主卡中扣除*/), sqlcon);
                        sqlcom.Connection = sqlcon;
                        sqlcom.Transaction = transaction;
                        sqlcom.ExecuteNonQuery();
                        //更新油卡明细表。
                        sqlstr = @"
insert into youkaguanli_card_detail(changetime,amount,balance,addname,addip,planid,cardid,inout,jgname,bzname,carnum,currentowner)
select top(1) cast('{0}'as smalldatetime) ,{1},case when d.cardid='0' or d.balance is null then c.balance else d.balance end+({1}),'{2}','{3}',{4},'{5}',1,c.jgname,c.bzname,c.carnum,c.owner
from youkaguanli_card as c left join youkaguanli_card_detail as d on  c.cardnum = d.cardid
where (d.changetime is null or d.changetime<=cast('{0}'as smalldatetime)) and c.cardnum='{5}'
order by d.changetime desc,d.addtime desc,d.id desc";//on  c.cardnum = d.cardidor d.cardid='0'
                        //时间为领取时间，操作人为当前用户。分卡的分拨操作人为领取人。
                        sqlcom = new SqlCommand(string.Format(sqlstr, lingqutime, jine, lingquren, Page.Request.UserHostAddress.ToString().Trim(), id, card), sqlcon);
                        sqlcom.Connection = sqlcon;
                        sqlcom.Transaction = transaction;
                        sqlcom.ExecuteNonQuery();
                        //    更新之后的记录，更新油卡余额,因为刚添加的一定是changetime所在天的最后一条，因此只需更新日期之后的
                        sqlstr = @"UPDATE t SET balance = balance +({1})
FROM (select ROW_NUMBER() over (order by changetime desc,addtime desc,id desc) as i,ka.*
from youkaguanli_card_detail as ka where cardid='{2}') t
where changetime>cast('{0}'as smalldatetime)";
                        sqlcom = new SqlCommand(string.Format(sqlstr, lingqutime, jine, card), sqlcon);
                        sqlcom.Connection = sqlcon;
                        sqlcom.Transaction = transaction;
                        sqlcom.ExecuteNonQuery();
                        //    更新之后的记录，更新油卡余额,因为刚添加的一定是changetime所在天的最后一条，因此只需更新日期之后的
                        //    不更新油卡表里的余额，将油卡表里的余额视为初始金额。
                        sqlstr = @"UPDATE youkaguanli_card SET balance = balance +({0}) where cardnum='{1}'";
                        sqlcom = new SqlCommand(string.Format(sqlstr, jine, card), sqlcon);
                        sqlcom.Connection = sqlcon;
                        sqlcom.Transaction = transaction;
                        sqlcom.ExecuteNonQuery();
                    }
                    //更新管理表
                    string sqlstr2 = "update ranyouxiaohao set cailiaoname='" + Label2.Text + "',cailiaotime='" + DateTime.Now.ToString() + "',cailiaoip='" + Page.Request.UserHostAddress.ToString().Trim() + "',zt=5 where id=" + Request.QueryString["id"];
                    sqlcom = new SqlCommand(sqlstr2, sqlcon);
                    sqlcom.Connection = sqlcon;
                    sqlcom.Transaction = transaction;
                    sqlcom.ExecuteNonQuery();

                    transaction.Commit();
                }
                catch (Exception ex)
                {
                    issuccess = false;
                    transaction.Rollback();
                }
                finally { transaction.Dispose(); sqlcon.Close(); }
            }
        }
        catch (SqlException)
        {
            issuccess = false;
            throw;
        }

        string jinggao3 = "<SCRIPT language=javascript>alert('";
        jinggao3 += issuccess ? "受理操作成功！" : "受理操作失败！";
        jinggao3 += "');</SCRIPT>";
        ClientScript.RegisterStartupScript(this.GetType(), "aa3", jinggao3);
        ClientScript.RegisterStartupScript(this.GetType(), "aa4", "<SCRIPT language=javascript>document.location.href='clk_shoulilist.aspx';</SCRIPT>");

    }
    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            e.Row.Attributes.Add("onmouseover", "c=this.style.backgroundColor;this.style.backgroundColor='#D1DDF1'");
            e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=c");
        }
        if (e.Row.RowIndex != -1)
        {
            int id = e.Row.RowIndex + 1;
            e.Row.Cells[0].Text = id.ToString();
        }

    }

}